package vector

import (
	"context"
	"fmt"
	"time"

	"github.com/qdrant/go-client/qdrant"
	"go-file-perception-model/internal/logger"
)

// QdrantClient Qdrant客户端管理器
type QdrantClient struct {
	client     *qdrant.Client
	timeout    time.Duration
	collection string
}

// NewQdrantClient 创建Qdrant客户端实例
func NewQdrantClient(host string, port int) (*QdrantClient, error) {
	return NewQdrantClientWithAPIKey(host, port, "")
}

// NewQdrantClientWithAPIKey 创建带有API密钥的Qdrant客户端实例
func NewQdrantClientWithAPIKey(host string, port int, apiKey string) (*QdrantClient, error) {
	fmt.Printf("[QdrantClient] Creating new client for host: %s, port: %d\n", host, port)
	
	// 创建Qdrant客户端
	config := &qdrant.Config{
		Host: host,
		Port: port,
	}
	
	// 如果提供了API密钥，则设置认证信息
	if apiKey != "" {
		config.APIKey = apiKey
		fmt.Printf("[QdrantClient] Using API key authentication\n")
	} else {
		fmt.Printf("[QdrantClient] No API key provided, using unauthenticated connection\n")
	}
	
	client, err := qdrant.NewClient(config)
	if err != nil {
		fmt.Printf("[QdrantClient] Error creating client: %v\n", err)
		return nil, fmt.Errorf("failed to create Qdrant client: %w", err)
	}

	// 测试连接
	fmt.Printf("[QdrantClient] Testing connection to Qdrant server...\n")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 检查服务是否可用
	collections, err := client.ListCollections(ctx)
	if err != nil {
		fmt.Printf("[QdrantClient] Connection test failed: %v\n", err)
		return nil, fmt.Errorf("failed to connect to Qdrant server: %w", err)
	}

	fmt.Printf("[QdrantClient] Connection successful, found %d collections\n", len(collections))
	for i, coll := range collections {
		if i < 5 { // 只显示前5个集合名称
			fmt.Printf("[QdrantClient] Collection %d: %s\n", i+1, coll)
		}
	}

	fmt.Printf("[QdrantClient] Client connected successfully, host: %s, port: %d\n", host, port)

	return &QdrantClient{
		client:     client,
		timeout:    30 * time.Second,
		collection: "", // 初始为空，需要通过SetCollection设置
	}, nil
}

// GetClient 获取原始Qdrant客户端
func (c *QdrantClient) GetClient() *qdrant.Client {
	return c.client
}

// SetCollection 设置当前使用的集合
func (c *QdrantClient) SetCollection(collectionName string) {
	if collectionName == "" {
		fmt.Printf("[QdrantClient] Warning: Empty collection name provided, using default 'file_chunks'\n")
		c.collection = "file_chunks"
	} else {
		fmt.Printf("[QdrantClient] Setting collection to: %s\n", collectionName)
		c.collection = collectionName
	}
}

// GetCollection 获取当前使用的集合名称
func (c *QdrantClient) GetCollection() string {
	if c.collection == "" {
		// 如果集合名称为空，返回一个默认值，但记录警告日志
		fmt.Printf("[QdrantClient] Warning: Collection name is empty, using default name 'file_chunks'\n")
		return "file_chunks"
	}
	return c.collection
}

// SetTimeout 设置操作超时时间
func (c *QdrantClient) SetTimeout(timeout time.Duration) {
	c.timeout = timeout
}

// GetTimeout 获取操作超时时间
func (c *QdrantClient) GetTimeout() time.Duration {
	return c.timeout
}

// Close 关闭客户端连接
func (c *QdrantClient) Close() error {
	// Qdrant客户端不需要显式关闭
	logger.Info("Qdrant client closed")
	return nil
}

// IsConnected 检查客户端是否连接
func (c *QdrantClient) IsConnected(ctx context.Context) bool {
	_, err := c.client.ListCollections(ctx)
	return err == nil
}